package com.finalist.util;

import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.awt.image.CropImageFilter;
import java.awt.image.FilteredImageSource;
import java.awt.image.ImageFilter;
import java.io.File;
import java.util.Iterator;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.plugins.jpeg.JPEGImageWriteParam;
import javax.imageio.stream.ImageOutputStream;

import org.apache.log4j.Logger;

public class ImageUtil {
	
	protected static Logger logger = Logger.getLogger(ImageUtil.class);
	
    
    private static float getCompressQuality(long size) {
    	if(size >= 1024 * 1024 * 2) {
    		return 0.5f;
    	} else if(size >= 1024 * 1024) {
    		return 0.6f;
    	} else if(size >= 1024 * 512) {
    		return 0.8f;
    	}
    	
    	return 0.9f;
    }
 
   /**
    * 图片压缩，先判断图片大小如果大小500K，就自动压缩
    * @param srcFile
    * @param width
    * @param height
    * @param destFile
    */
    public static void scaleAndcompressImage(File srcFile, int width, int height, File destFile) {
    	try {
			File src =srcFile;
			File dest = destFile;
			BufferedImage im = ImageIO.read(src);
			String format =src.getName().substring(src.getName().lastIndexOf(".") + 1);
			
			// 先进行缩放处理
			double rate = 0, rate1 = 0, rate2 = 0;
			if(width > 0) {
				if(width > im.getWidth()) {
					rate1 = 1;
				} else {
					rate1 = ((double) im.getWidth(null)) / (double) width;
				}
			} 
			if(height > 0) {
				if(height > im.getHeight()) {
					rate2 = 1;
				} else {
					rate2 = ((double) im.getHeight(null)) / (double) height;
				}
			}
			rate = Math.max(rate1, rate2);
			if(rate == 0) {
				throw new IllegalArgumentException("width or height are both zero");
			}
			
			int new_w = (int) (((double) im.getWidth(null)) / rate);
			int new_h = (int) (((double) im.getHeight(null)) / rate);
			
			BufferedImage tag = new BufferedImage(new_w, new_h, BufferedImage.TYPE_INT_RGB);
			tag.getGraphics().drawImage(im.getScaledInstance(new_w, new_h, BufferedImage.SCALE_SMOOTH), 0, 0, null);
			ImageIO.write(tag, format, dest);
			
			float quality = getCompressQuality(dest.length());
			
			Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName("jpg");
			ImageWriter writer = (ImageWriter) writers.next();
			ImageOutputStream ios = ImageIO.createImageOutputStream(dest);
			writer.setOutput(ios);

			JPEGImageWriteParam jpegParams = new JPEGImageWriteParam(null);
			jpegParams.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
			jpegParams.setCompressionQuality(quality);
			
			writer.write(null, new IIOImage(tag, null, null), jpegParams);
			
			ios.close();
			writer.dispose();
		} catch(Exception e) {
			logger.error("image scaleAndcompressImage error : ", e);
		}
    }
    public static String getExtension(String fileName) {
		return fileName.substring(fileName.lastIndexOf(".") + 1);
	}
    /**
     * 对图按比例进行缩放
     * @param srcFile  被缩放的图片路径
     * @param destFile 缩放后的图片路径
     * @param width 缩放的宽度，宽度会根据缩放比例计算出来, 为0时，则以height为准
     * @param height 缩放的高度，高度会根据缩放比例计算出来, 为0时，则以width为准
     */
    public static void scaleImagePercently(File  srcFile, File destFile, int width, int height) {
    	try {
			File f = srcFile;
			BufferedImage im = ImageIO.read(f);
			String format =f.getName().substring(f.getName().lastIndexOf(".") + 1);

			double rate = 0, rate1 = 0, rate2 = 0;
			if(width > 0) {
				if(width > im.getWidth()) {
					rate1 = 1;
				} else {
					rate1 = ((double) im.getWidth(null)) / (double) width;
				}
			} 
			if(height > 0) {
				if(height > im.getHeight()) {
					rate2 = 1;
				} else {
					rate2 = ((double) im.getHeight(null)) / (double) height;
				}
			}
			rate = Math.max(rate1, rate2);
			if(rate == 0) {
				throw new IllegalArgumentException("width or height are both zero");
			}
			
			int new_w = (int) (((double) im.getWidth(null)) / rate);
			int new_h = (int) (((double) im.getHeight(null)) / rate);
			
			BufferedImage tag = new BufferedImage(new_w, new_h, BufferedImage.TYPE_INT_RGB);
			tag.getGraphics().drawImage(im.getScaledInstance(new_w, new_h, BufferedImage.SCALE_SMOOTH), 0, 0, null);
			
			ImageIO.write(tag, format, destFile);
		} catch(Exception e) {
			logger.error("image scaleImagePercently error : ", e);
		}
    }
    
    /**
     * 对图按比例进行缩放
     * @param srcFile  被缩放的图片路径
     * @param width 缩放的宽度，宽度会根据缩放比例计算出来, 为0时，则以height为准
     * @param height 缩放的高度，高度会根据缩放比例计算出来, 为0时，则以width为准
     */
    public static void scaleImagePercently(File srcFile, int width, int height) {
    	scaleImagePercently(srcFile, srcFile, width, height);
    }

    public static void main(String[] args) {
		String src = "f:\\src.jpg";
		String dest = "f:\\dest.jpg";
		//compressImage(src, dest);
		//scaleImagePercently(src, 800, 0);
		//scaleAndcompressImage(src, 960, 640, dest);
	}
    
}
